﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;
using System.Data.SqlClient;
using Enterprise.Modules;
using System.Reflection;

namespace Enterprise.ClientWeb.Controls
{
    public partial class Region : System.Web.UI.UserControl
    {
        private string _ID;
        private bool isAdmin = true;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
                FillList();
        }

        private void FillList()
        {
            Hashtable list = new Hashtable();
            Assembly[] dlls = AppDomain.CurrentDomain.GetAssemblies();
            moduleList.Items.Clear();

            foreach (Assembly a in dlls)
            {
                foreach (Type t in a.GetTypes())
                {
                    if (t.IsClass && (t.GetInterface("IModule") != null) && (!t.IsAbstract))
                    {
                        if (!list.ContainsKey(t.Name))
                            list.Add(t.Name, t.AssemblyQualifiedName);
                    }
                }
            }

            SortedList sortedlist = new SortedList(list);
            for (int i = 0; i < sortedlist.Count; i++)
            {
                string[] name = sortedlist.GetByIndex(i).ToString().Split(',');
                string listname = name[0].Replace("Enterprise.Modules.", "");
                string ResourceID = "md_" + listname + "_Title";
                string moduleName = Resources.Resource.ResourceManager.GetString(ResourceID);
                moduleList.Items.Add(new ListItem(moduleName, sortedlist.GetByIndex(i).ToString()));
            }
            moduleList.Items.Insert(0, new ListItem(Resources.Resource.drpChooseModule, ""));
        }


        /// <summary>
        /// It has to be unique since this is inserted into a database as 
        /// identification for other usercontrols that this Region will hold.
        /// </summary>
        public string RegionID
        {
            get{return this._ID;}
            set{this._ID = value;}
        }


        /// <summary>
        /// Get all modules that belong to this Region
        /// </summary>
        public List<IModule> LoadModules()
        {
            string PageID = HttpContext.Current.Request["PageID"];

            if (string.IsNullOrEmpty(PageID))
                PageID = Config.GetStartPageID();

            List<IModule> moduleList = new List<IModule>();

            SqlConnection Conn = new SqlConnection(Config.ConnectionString()); //The PortalID in sql is going to be used later.
            SqlCommand command = new SqlCommand(string.Format("SELECT * FROM Objects WHERE PageID={0} AND RegionID='{1}' AND PortalID=1 ORDER BY SortOrder", PageID, RegionID.Trim()), Conn);
           
            Conn.Open();
            SqlDataReader dr = command.ExecuteReader();

            try
            {
                while (dr.Read())
                {
                    IModule module = ModuleLoader.GetInstance().LoadModule(dr["id"].ToString().Trim());
                    moduleList.Add(module);
                }
            }
            finally { Conn.Close(); }

            return moduleList;
        }


        /// <summary>
        /// Loads all modules in this Region and adds it to the placeholder.
        /// </summary>
        /// <param name="e"></param>
        protected void Page_Init(object sender, EventArgs e)
        {
            Page.Response.Expires = 0;
            Page.Response.ExpiresAbsolute = DateTime.Now.AddMinutes(-1.0);
            Page.Response.CacheControl = "private";
            Page.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            
            moduleHolder.Controls.Clear();

            List<IModule> moduleList = LoadModules();
           
            try
            {
                foreach (IModule module in moduleList)
                {
                    ModuleBase ctl = (ModuleBase)LoadControl(module.UserControl);

                    if (isAdmin)
                        moduleHolder.Controls.Add(new LiteralControl("\n<div class=\"modulelines\">"));

                    if (isAdmin)
                    {
                        //Admin (Role management) features will be added later
                        UserControl control = (UserControl)LoadControl("~/Module/ModuleController.ascx");
                        ((ModuleAdmin)control).Module = ctl;
                        ((ModuleAdmin)control).RegionID = RegionID;
                        ((ModuleAdmin)control).ModuleID = module.ModuleId;
                        
                        moduleHolder.Controls.Add(control);
                    }

                    moduleHolder.Controls.Add(ctl);
                    ctl.Module = module;

                    if (isAdmin)
                        moduleHolder.Controls.Add(new LiteralControl("\n</div>\n"));
                }
            }
            catch (Exception ex) { throw ex; }
        }

        /// <summary>
        /// Adds a new Module to this Region
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void AddModule(object sender, EventArgs e)
        {
            if (moduleList.SelectedValue != string.Empty)
            {
                IModule newSection = (IModule)Activator.CreateInstance(Type.GetType(moduleList.SelectedValue));
                newSection.SaveData(RegionID);
                Response.Redirect(Request.RawUrl);
            } 
        }
    }
}